package com.ff.common.util.file;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Author:Wish
 * @Date: Created in 2018/9/6 18:24
 **/
public class FileExportUtil {
    public static void fileExport(HttpServletResponse response, File file) {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        String fileName = file.getName();
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        try {
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            inputStream = new FileInputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf);
            }
            outputStream.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
